package com.estronger.shopmanage.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.czt.mp3recorder.MP3Recorder;
import com.estronger.shopmanage.R;
import com.estronger.shopmanage.base.MyApplication;
import com.estronger.shopmanage.manager.NetManager;
import com.estronger.shopmanage.utils.MediaRecordFunc;
import com.estronger.shopmanage.utils.MedialPlayerFunc;
import com.estronger.shopmanage.utils.Toast;
import com.lidroid.xutils.http.RequestParams;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;


/**
 * 增加图片
 */
public class YesRecordView extends LinearLayout implements View.OnClickListener {

    private Activity mContext;
    private View rootView;
    private RelativeLayout rl_voice_layout;//客户证言录音
    private TextView tv_voice_second;
    private ImageView iv_voice_button, iv_delete_record, iv_open_recorder;
    private PopupWindow recordPop;

    private MediaRecordFunc mrFunc;

    private ActionListener actionListener;

    public YesRecordView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        View view = View.inflate(context, R.layout.view_yes_record, this);
        findViewById(view);
    }

    private void findViewById(View view) {
        rl_voice_layout = (RelativeLayout) findViewById(R.id.voice_layout);
        tv_voice_second = (TextView) view.findViewById(R.id.voice_second_tv);
        iv_voice_button = view.findViewById(R.id.iv_voice_button);
        iv_delete_record = view.findViewById(R.id.iv_delete_record);
        iv_open_recorder = view.findViewById(R.id.iv_open_recorder);
        iv_voice_button.setOnClickListener(this);
        iv_delete_record.setOnClickListener(this);
        iv_open_recorder.setOnClickListener(this);
        mrFunc = MediaRecordFunc.getInstance();
    }

    /**
     * 初始化界面
     *
     * @param activity
     */
    public void initView(Activity activity, View view, ActionListener actionListener) {
        this.mContext = activity;
        this.rootView = view;
        this.actionListener = actionListener;
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_voice_button) {
            //播放录音
            playVoice(v);
        }else if (v.getId() == R.id.iv_delete_record) {
            //删除录音
            deleteRecord();
        }else if (v.getId() == R.id.iv_open_recorder) {
            //打开录音弹框
            openRecorder();
        }else if (v.getId() == R.id.record_cansel) {
            //取消录音
            dissmissRecord();
        }else if (v.getId() == R.id.iv_re_record) {
            //开始录音
            reRecord();
        }else if (v.getId() == R.id.record_pause) {
            //继续录音
            pauseRecord();
        }else if (v.getId() == R.id.record_save) {
            //保存录音
            saveRecord();
        }
    }

    private MedialPlayerFunc mPlayer;

    public void playVoice(final View view) {
        if (null == mPlayer) {
            mPlayer = MedialPlayerFunc.getInstance();
        }
        if (mPlayer.getIsPlaying()) {// 正在播放时的处理
            mPlayer.pause();
            stopAnim(view);
        } else {
            if (null != view.getTag()) {
                view.setVisibility(View.INVISIBLE);
                mPlayer.start(view.getTag().toString(),
                        new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mp) {
                                view.setVisibility(View.VISIBLE);
                                stopAnim((View) view.getParent());
                                mPlayer.setPlaying(false);
                                // Toast.show(mActivity,
                                // "播放完毕", 0).show();
                            }
                        });
                startAnim((View) view.getParent());
                mPlayer.setPlaying(true);
            }
        }
    }
    public void deleteRecord() {
        rl_voice_layout.setVisibility(View.GONE);
        resetRecord();
    }


    public void openRecorder() {
        if (rl_voice_layout.getVisibility() == View.VISIBLE) {
            Toast.show(mContext, "暂时只支持上传一个录音文件", 2000);
            return;
        }
        if (recordPop == null) {
            initRecordPop();
        }
        showRecordPop(rootView);
    }

    public void dissmissRecord() {
        resetRecord();
    }

    public void resetRecord() {
        MP3Recorder.status = MP3Recorder.Status.STATUS_NO_READY;
        mrFunc.stop();
        countTime = 0;
        keep = false;
        if (null != counterTimer)
            counterTimer.cancel();
        counterTimer = null;
        counterTask = null;
        isRecording = false;
        recordTime.setText("00:00");
        if (null != recordPop)
            recordPop.dismiss();
        recordPop = null;
    }



    @SuppressLint("ResourceType")
    public void startAnim(View view) {
        view.setBackgroundResource(R.anim.play_voice_ani);
        rocketAnimation = (AnimationDrawable) view.getBackground();
        rocketAnimation.start();
    }

    AnimationDrawable rocketAnimation;

    public void stopAnim(View view) {
        if (rocketAnimation != null) {
            rocketAnimation.stop();
        }
        view.setVisibility(View.VISIBLE);
        mPlayer.setPlaying(false);
        view.setBackgroundResource(R.drawable.voice_article_icon);
    }

    int countTime = 0, upCountTime = 0;
    private boolean keep = true;
    private Timer counterTimer = new Timer();
    private TimerTask counterTask;

    private void count() {
        counterTask = new TimerTask() {
            @Override
            public void run() {
                MyApplication.getHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        if (keep) {
                            countTime++;
                            String timeText;
                            if ((countTime % 60) < 10) {
                                timeText = (countTime / 60) + ":0"
                                        + (countTime % 60);
                            } else {
                                timeText = (countTime / 60) + ":"
                                        + (countTime % 60);
                            }
                            recordTime.setText(timeText);
                        }
                    }
                });
            }
        };
        if (null == counterTimer)
            counterTimer = new Timer();
        counterTimer.schedule(counterTask, 1000, 1000);
    }
    private TextView recordTime, record_cansel;
    private ImageView start_record, record_pause, iv_re_record;
    private TextView tvfRecord, tvfRecordM, record_save;

    public void initRecordPop() {
        recordPop = new PopupWindow(this);
        View view = LayoutInflater.from(mContext).inflate(
                R.layout.popwindow_record, null);

        recordPop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        recordPop.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        recordPop.setBackgroundDrawable(new BitmapDrawable());
        recordPop.setFocusable(true);
        recordPop.setOutsideTouchable(true);
        recordPop.setContentView(view);

        recordTime = (TextView) view.findViewById(R.id.pop_record_time);
        record_cansel = view.findViewById(R.id.record_cansel);
        start_record = (ImageView) view.findViewById(R.id.start_record);
        record_pause = view.findViewById(R.id.record_pause);
        tvfRecord = view.findViewById(R.id.tvfRecord);
        iv_re_record = view.findViewById(R.id.iv_re_record);
        record_save = view.findViewById(R.id.record_save);
        tvfRecordM = view.findViewById(R.id.tvfRecordM);
        recordPop.setAnimationStyle(R.style.pop_login);
        iv_re_record.setOnClickListener(YesRecordView.this);
        record_pause.setOnClickListener(YesRecordView.this);
        record_cansel.setOnClickListener(YesRecordView.this);
        record_save.setOnClickListener(YesRecordView.this);
    }



    public void showRecordPop(View parentView) {
        recordPop.showAtLocation(parentView, Gravity.CENTER, 0, 0);
    }

    private boolean isRecording = false;
    private String recordLength = "00:00";



    private boolean currPause = false;

    public void pauseRecord() {
        if (isRecording) {
            recordLength = recordTime.getText().toString();
            upCountTime = countTime;
            actionListener.updateUpTime(upCountTime);
            keep = false;
            currPause = true;
            // view.setBackgroundResource(R.drawable.recording_start_icon);
            record_pause.setBackgroundResource(R.drawable.recording_suspended_icon);
            tvfRecord.setVisibility(View.GONE);
            tvfRecordM.setText("录音完成");
            mrFunc.stop();
            return;
        }
        record_pause.setBackgroundResource(R.drawable.recording_start_icon);
        tvfRecord.setText("结束");
        tvfRecordM.setText("录音中...");
        tvfRecord.setVisibility(View.VISIBLE);
        tvfRecordM.setVisibility(View.VISIBLE);
        isRecording = true;
        keep = true;
        mrFunc.start(mContext);
        count();
    }

    public void reRecord() {
        keep = false;
        countTime = 0;
        recordTime.setText("0:00");
        isRecording = false;
        //start_record.setBackgroundResource(R.drawable.recording_1_icon);
        record_pause.setBackgroundResource(R.drawable.recording_suspended_icon);
        tvfRecord.setText("开始");
        tvfRecordM.setVisibility(View.GONE);
        tvfRecord.setVisibility(View.VISIBLE);
        if (counterTask != null) {
            counterTask.cancel();
        }
        mrFunc.stop();
    }

    //保持录音
    private String mp3Path;
    public void saveRecord() {
        if (recordTime.getText().toString().equals("0:00")) {
            Toast.show(mContext, "请完成录音之后再保存", 2000);
            return;
        }

        if (keep) {
            Toast.show(mContext, "请先结束录音再保存", 2000);
            return;
        }

        mp3Path = mrFunc.getAMRFilePath();
        if (TextUtils.isEmpty(mp3Path)) {
            Toast.show(mContext, "没有录音文件", 2000);
        } else {
            actionListener.saveRecord(mp3Path);
        }
    }

    public void afterSave(String recordPath) {
        // recordTime.getText().toString();
        String voiceText = recordLength.replace(":", "'") + "\"";
        tv_voice_second.setText(voiceText);
        iv_voice_button.setTag(recordPath);
        rl_voice_layout.setVisibility(View.VISIBLE);
        // record_tip.setVisibility(View.GONE);
        resetRecord();
    }

    public void destory() {
        if (recordPop != null && recordPop.isShowing()) {
            recordPop.dismiss();
            resetRecord();
        }
    }

    public void clear() {
        countTime = 0;
        keep = true;
        counterTimer = null;
        counterTask = null;
        isRecording = false;
    }

    public interface ActionListener {
        void saveRecord(String recordPath);
        void updateUpTime(int upTime);
    }

}